# Import all required libraries
from python_a2a.mcp import FastMCP, text_response
import threading
import requests
import re
import yfinance as yf

# DuckDuckGo MCP Server for ticker lookup
duckduckgo_mcp = FastMCP(
    name="DuckDuckGo MCP",
    version="1.0.0",
    description="Search capabilities for finding stock information"
)

@duckduckgo_mcp.tool()
def search_ticker(company_name: str) -> str:
    """Find stock ticker symbol for a company using DuckDuckGo search."""
    print(f"Searching for ticker symbol for {company_name}...")
    # Implementation details (simplified)
    query = f"{company_name} stock ticker symbol"
    url = f"https://api.duckduckgo.com/?q={query}&format=json"
    response = requests.get(url)
    data = response.json()
    
    # Extract ticker from results
    # Look for patterns like "NYSE: AAPL" or "NASDAQ: MSFT"
    text = data.get("Abstract", "")
    ticker_match = re.search(r'(?:NYSE|NASDAQ):\s*([A-Z]+)', text)
    if ticker_match:
        return ticker_match.group(1)
    
    # Fall back to common tickers for demo purposes
    if company_name.lower() == "apple":
        return "AAPL"
    elif company_name.lower() == "microsoft":
        return "MSFT"
    elif company_name.lower() == "google" or company_name.lower() == "alphabet":
        return "GOOGL"
    elif company_name.lower() == "amazon":
        return "AMZN"
    elif company_name.lower() == "tesla":
        return "TSLA"
    
    return f"Could not find ticker for {company_name}"


if __name__ == "__main__":
    # Run this agent on port 5001
    duckduckgo_mcp.run(host="localhost", port=5001) 